package heap;

import java.io.IOException;


import java.io.IOException;

import Transaction.Transaction;

import Common.Convert;
import Common.GlobalConst;

import storage.data.PageID;



public class DataPageInfo implements GlobalConst {
	int availspace;

	int reccnt;

	PageID pageId = new PageID();

	private byte[] data;

	public static final int size = 12;
	
	private int offset;

	public DataPageInfo() {

		data = new byte[12];
		int availapace = 0;
		reccnt = 0;
		pageId.pageId = INVALID;
		offset = 0;
	}

	public DataPageInfo(byte[] array) {
		data = array;
		offset = 0;
	}

	public byte[] returnByteArray() {
		return data;
	}

	public DataPageInfo(Tuple atuple,Transaction tx,String table) 
			throws Exception {
		// need check _atuple size == this.size ?otherwise, throw new exception
		if (atuple.getLength() != 12) {
		}

		else {
			data = atuple.returnTupleByteArray();
			offset = atuple.getOffset();

			availspace = Convert.getIntValue(offset, data,tx,table);
			reccnt = Convert.getIntValue(offset + 4, data,tx,table);
			pageId = new PageID();
			pageId.pageId = Convert.getIntValue(offset + 8, data,tx,table);

		}
	}
	
	/**
	 * convert this class objcet to a tuple(like cast a DataPageInfo to Tuple)
	 * 
	 * 
	 */
	public Tuple convertToTuple(Transaction tx, String table,PageID pid) throws Exception {

		// 1) write availspace, recct, pageId into data []
		Convert.setIntValue(availspace, offset, data,tx,table,pid);
		Convert.setIntValue(reccnt, offset + 4, data,tx,table,pid);
		Convert.setIntValue(pageId.pageId, offset + 8, data,tx,table,pid);

		// 2) creat a Tuple object using this array
		Tuple atuple = new Tuple(data, offset, DATAINFOPAGESIZE);
		// 3) return tuple object
		return atuple;

	}
	
	/** write this object's useful fields(availspace, recct, pageId) 
	   *  to the data[](may be in buffer pool)
	   *  
	   */
	  public void flushToTuple(Transaction tx, String table,PageID pid) throws Exception
	  {
	     // write availspace, recct, pageId into "data[]"
	    Convert.setIntValue(availspace, offset, data,tx,table,pid);
	    Convert.setIntValue(reccnt, offset+4, data,tx,table,pid);
	    Convert.setIntValue(pageId.pageId, offset+8, data,tx,table,pid);

	    // here we assume data[] already points to buffer pool
	  
	  }
}
